// 引入 用来发送请求的方法，路径要补全
var util = require('../../utils/util');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    formats: {},
    readOnly: false,
    placeholder: '开始输入你的感悟...',
    editorHeight: 300,
    keyboardHeight: 0,
    isIOS: false,
    index:0,
    // 图片信息
    topicImgs: []
  },

  // 取消按钮
  cancelHandle: function(){
    wx.showModal({
      content: '您确定要退出吗',
      cancelColor: '#333333',
      confirmColor: '#477FF7',
      success: function(res){
        if(res.confirm){
          wx.navigateBack({
            delta: 1,
          })
        }
      }
    });
  },

  // 提交表单（校验表单、上传数据、上传图片）
  handleSubmitForm:function(e){
    let that = this;
    let data = e.detail.value;
    let {theme} = data;
    let userId = wx.getStorageSync('userInfo').id;
    // 校验表单
    if(theme == ''){
      this.verifyForm("感悟标题");
      return;
    }
    this.editorCtx.getContents({
      success: function(res){
        console.log("富文本信息", res);
        const {html, text} = res;
        if(html == ''){
          that.verifyForm("感悟内容");
        }else{
          that.addTopic({
            theme,
            description: text,
            richText: html,
            userId
          });
        }
      }
    });
  },

   // 保存感悟信息
  addTopic(data){
    const {topicImgs} = this.data;
    if(topicImgs.length > 0){
      const topicImgList = [];
      topicImgs.forEach(function(imgSrc){
        topicImgList.push({imgSrc});
      });
      data['topicImgList'] = topicImgList;
    }
    wx.request({
      url: `${util.BASE_URL}topic/addTopic`,
      method: 'POST',
      data,
      success: function(res){
        console.log('发布帖子', res);
        if(res.data.success){
          util.success(function(){
            wx.navigateTo({
              url: '/pages/forum/forum',
            })
          });
        }else{
          util.error();
        }
      }
    })
  },

  // 校验表单，并给出提示信息
  verifyForm:function(content){
    wx.showToast({
      title: content +　'不能为空！',
      icon: 'none',
      duration:2000
    })
  },




  readOnlyChange() {
    this.setData({
      readOnly: !this.data.readOnly
    })
  },
  updatePosition(keyboardHeight) {
    const toolbarHeight = 120
    const { windowHeight, platform } = wx.getSystemInfoSync()
    let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight) : (windowHeight - 140 )
    this.setData({ editorHeight, keyboardHeight })
  },
  calNavigationBarAndStatusBar() {
    const systemInfo = wx.getSystemInfoSync()
    const { statusBarHeight, platform } = systemInfo
    const isIOS = platform === 'ios'
    const navigationBarHeight = isIOS ? 44 : 48
    return statusBarHeight + navigationBarHeight
  },
  onEditorReady() {
    const that = this
    wx.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context
    }).exec()
  },
  blur() {
    this.editorCtx.blur()
  },
  format(e) {
    let { name, value } = e.target.dataset
    if (!name) return
    // console.log('format', name, value)
    this.editorCtx.format(name, value)

  },
  onStatusChange(e) {
    const formats = e.detail
    this.setData({ formats })
  },
  insertDivider() {
    this.editorCtx.insertDivider({
      success: function () {
        console.log('insert divider success')
      }
    })
  },
  clear() {
    this.editorCtx.clear({
      success: function (res) {
        console.log("clear success")
      }
    })
  },
  removeFormat() {
    this.editorCtx.removeFormat()
  },
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },
  insertImage() {
    const that = this
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      sizeType: ['compressed'],
      success: function (res) {
        console.log("选择的图片", res);
        that.uploadFile([res.tempFiles[0].tempFilePath]);
      }
    })
  },

  // 上传插入的图片
  uploadFile(imgList){
    const that = this;
    util.uploadFileToOss(`forum`, imgList, function(pathList){
      console.log("上传成功后的图片", pathList);
      const {topicImgs} = that.data;
      topicImgs.push(pathList[0]);
      that.setData({
        topicImgs
      });
      that.editorCtx.insertImage({
        src: pathList[0],
        data: {
          id: new Date().getTime(),
          role: 'god'
        },
        width: '80%',
        success: function () {
          console.log('insert image success')
        }
      })
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const platform = wx.getSystemInfoSync().platform
    const isIOS = platform === 'ios'
    this.setData({ isIOS})
    const that = this
    this.updatePosition(0)
    let keyboardHeight = 0
    wx.onKeyboardHeightChange(res => {
      if (res.height === keyboardHeight) return;
      const duration = res.height > 0 ? res.duration * 1000 : 0
      keyboardHeight = res.height
      setTimeout(() => {
        wx.pageScrollTo({
          scrollTop: 0,
          success() {
            that.updatePosition(keyboardHeight)
            that.editorCtx.scrollIntoView()
          }
        })
      }, duration)

    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})